package softtech.apps.customadapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import softtech.apps.autoanswerphonecall.R;
import softtech.apps.model.Contact;
import softtech.apps.model.RowVoiceRecorded;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

public class ItemVoiceRecordAdapter extends BaseAdapter implements Filterable {

	Context mContext;

	private List<RowVoiceRecorded> list;

	private List<RowVoiceRecorded> database = new ArrayList<RowVoiceRecorded>();

	private List<Contact> listContacts;

	public ItemVoiceRecordAdapter(Context context, List<RowVoiceRecorded> lst) {
		// TODO Auto-generated constructor stub
		this.mContext = context;
		list = new ArrayList<RowVoiceRecorded>();
		list = lst;
		database.clear();
		database = list;
	}

	public void updateAdapter(List<RowVoiceRecorded> lst) {
		list = lst;
		notifyDataSetChanged();
	}
	public Boolean removeItem(int position) {
		String file_path = list.get(position).getmPath();
		//Log.d("REMOVE", "File path = "+file_path);
		File file = new File(file_path);
		boolean deleted = file.delete();
		if (deleted) {
			list.remove(position);
			notifyDataSetChanged();
		}
		return deleted;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	public void dropData() {
		list.removeAll(list);
		notifyDataSetChanged();
	}
	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder viewHolder;
		if (convertView == null) {
			LayoutInflater mInflater = (LayoutInflater) mContext
					.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			convertView = mInflater
					.inflate(R.layout.item_lv_voice_record, null);
			viewHolder = new ViewHolder();

			viewHolder.imgAvatar = (ImageView) convertView
					.findViewById(R.id.imgAvatar);
			viewHolder.contactName = (TextView) convertView
					.findViewById(R.id.tvContactName);
			viewHolder.dateTime = (TextView) convertView
					.findViewById(R.id.tvTimeCreate);
			viewHolder.imgCloud = (ImageView) convertView
					.findViewById(R.id.imgCloud);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.contactName.setText(list.get(position).getmName());
		viewHolder.dateTime.setText(convertTime(list.get(position).getmTimeCreate()
				));
		
//		Log.e("IsSync", list.get(position).getIsSync()+"");
		if (list.get(position).getIsSync()) {
			// Show image da Sync
			viewHolder.imgCloud.setImageResource(R.drawable.ic_cloud_issync);
		} else {
			// Show image chua Sync
			viewHolder.imgCloud.setImageResource(R.drawable.ic_cloud);
		}
		// viewHolder.dateTime.setText(name);
		// duration.setText(row_pos.getmDuration());
		return convertView;
	}

	public void getContacts() {
		// Get all contact here
		ContentResolver cr = mContext.getContentResolver();
		Cursor cur = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		cur.moveToFirst();

		while (cur.moveToNext()) {
			String contactId = cur.getString(cur
					.getColumnIndex(ContactsContract.Contacts._ID));

			// Log.e("contact id"," contact id="+contactId);

			String name = cur
					.getString(cur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

			// String
			// phone=cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			// Log.e("name","name="+name);

			String hasPhone = null;
			int hasphone = -1;
			try {
				hasPhone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				hasphone = Integer.parseInt(hasPhone);
				// Log.e("contactID",contactId);
			} catch (Exception ex) {

				// Log.e("contactID",contactId);
			}
			if (hasphone > 0) {
				// Log.d("CONTACT", "Has phone number from SIM CARD");
				String phone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				Contact ct = new Contact(contactId, name, phone, contactId, 0);
				listContacts.add(ct);
			}
		}

	}

	private static class ViewHolder {
		public TextView contactName;
		public TextView dateTime;
		@SuppressWarnings("unused")
		public ImageView imgCloud;
		@SuppressWarnings("unused")
		public ImageView imgAvatar;
	}

	@Override
	public Filter getFilter() {
		return new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence charSequence) {
				FilterResults results = new FilterResults();
				// If there's nothing to filter on, return the original data for
				// your list
				if (charSequence == null || charSequence.length() == 0) {
					results.values = database;
					results.count = database.size();
				} else {
					List<RowVoiceRecorded> filterResultsData = new ArrayList<RowVoiceRecorded>();

					// if search details is 0, search fullName, else, search
					// all details

					for (RowVoiceRecorded c : database) {
						if (c.getmName().toLowerCase(Locale.ENGLISH)
								.contains(charSequence)) {
							filterResultsData.add(c);
						}
					}

					results.values = filterResultsData;
					results.count = filterResultsData.size();
				}

				return results;
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence charSequence,
					FilterResults filterResults) {
				// set the data to the filter results and notifyDataSetChanged()
				list = (List<RowVoiceRecorded>) filterResults.values;
				notifyDataSetChanged();
			}
		};
	}

	private String convertTime(long timeCreate) {

		String time = String.valueOf(timeCreate);

		// rename file
		String fileName[] = time.split("-");

		String name = "";
		// date
		// month
		name += fileName[0].substring(4, 6) + "-";
		// day
		name += fileName[0].substring(6, 8) + "-";
		// year
		name += fileName[0].substring(0, 4);

		name += " ";

		// hour
		name += fileName[0].substring(8, 10) + ":";
		name += fileName[0].substring(10, 12) + ":";
		name += fileName[0].substring(12, 14);

		return name;
	}
}
